package com.tedu.fallback;

import com.sun.xml.internal.ws.server.sei.MessageFiller;
import com.tedu.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/11/27
 */
@Component
public class ItemFB implements FallbackProvider {
    @Override
    public String getRoute() {
        return "item-service";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.FAILED_DEPENDENCY;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.FAILED_DEPENDENCY.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.FAILED_DEPENDENCY.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String json = JsonResult.ok("调用后台商品服务失败").toString();
                return new ByteArrayInputStream(json.getBytes("utf-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeader = new HttpHeaders();
                httpHeader.add("Content-Type","application/json;charset=UTF-8");
                return httpHeader;
            }
        };
    }
}
